<template>
  <div>
    <el-tree
      :data="deptList"
      :props="props"
      node-key="id"
      ref="treeForm"
      show-checkbox
      check-strictly
      :default-expanded-keys="[0]"
      @check-change="handleNodeClick"
    >
    </el-tree>
  </div>
</template>

<script>
import { tbDeptQueryDeptTreeList } from "@/api/admin/user/department-manage.js";
import Bus from "@/utils/bus.js";

export default {
  data() {
    return {
      props: {
        label: "name",
        children: "childList",
      },
      deptList: [{ name: "部门树", childList: [], id: 0 }],
      type: "2",
    };
  },
  props: {
    // 是否单选: true: 多选 false: 单选
    checkedType: {
      type: Boolean,
      default: true,
    },
  },
  mounted() {
    this.getDeptTree();
    Bus.$on("refreshList", () => {
      this.getDeptTree();
    });
  },
  methods: {
    getDeptTree() {
      tbDeptQueryDeptTreeList({ flag: 3, type: this.type }).then((res) => {
        if (res.data.code == 0) {
          this.deptList[0].childList = res.data.data;
        } else {
          this.$message.error(res.data.msg);
        }
      });
    },
    handleNodeClick(data, checked, node) {
      if (this.checkedType) return;
      if (checked === true) {
        this.checkedId = data.id;
        this.$refs.treeForm.setCheckedKeys([data.id]);
      } else {
        if (this.checkedId == data.id) {
          this.$refs.treeForm.setCheckedKeys([data.id]);
        }
      }
      let checkedData = this.$refs.treeForm.getCheckedNodes();
      Bus.$emit("selectedData", checkedData[0]);
    },
  },
};
</script>


